import __config from '../config/env'
const util = require('../utils/util.js')

const request = (url, method, data, showLoading) => {
  let _url = __config.basePath + url
  return new Promise((resolve, reject) => {
    if (showLoading) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: _url,
      method: method,
      data: data,
      header: {
        'client-type': 'MA', //客户端类型小程序
        'tenant-id': '1620403865897930752',
        'app-id': wx.getAccountInfoSync().miniProgram.appId, //小程序appId
        'third-session': wx.getStorageSync('third_session') != null ? wx.getStorageSync('third_session') : ''
      },
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.code != 0) {
            if (res.data.code == 60001) {
              //session过期，则清除过期session，并重新加载当前页
              if (!getApp().globalData.logining) {
                getApp().globalData.logining = true; //防止同时多个接口触发登录
                wx.removeStorageSync('third_session');
                setTimeout(function () {
                  getApp().globalData.logining = false;
                }, 5000);
                getApp().initPage().then(function (res) {
                  var pages = getCurrentPages(); // 获取页面栈
                  var currPage = pages[pages.length - 1]; // 当前页面
                  currPage.onLoad(currPage.options);
                  currPage.onShow();
                });
              }
              reject("session过期重新登录");
            } else if (res.data.code == 60002 || res.data.code == 60003) {
              var pages = getCurrentPages(); // 获取页面栈
              var currPage = pages[pages.length - 1]; // 当前页面
              if (currPage) {
                var curParam = currPage.options;
                // 拼接参数
                var reUrl = '/' + currPage.route;
                if (curParam != null) {
                  // 拼接参数
                  var param = '';
                  for (var key in curParam) {
                    param += '&' + key + '=' + curParam[key];
                  }
                  param = param.substr(1);
                  reUrl = reUrl + '?' + param;
                  reUrl = encodeURIComponent(reUrl);
                }
                wx.reLaunch({
                  url: '/pages/login/index?reUrl=' + reUrl
                });
              }
              reject("请先登录");
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.msg + '',
                showCancel: false,
                success: function success(res1) {
                  if (res.data.code == 80004) {
                    if (res1.confirm) {
                      wx.navigateBack({
                        delta: 1
                      });
                    }
                  }
                },
                complete: function complete() {}
              });
              reject(res.data.msg);
            }
          }
          resolve(res.data);
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            success: function success(res) {}
          });
          reject();
        } else if (res.statusCode == 502) {
          console.log(502);
          wx.showModal({
            title: '提示',
            content: '服务启维护中，请稍后再来',
            success: function success(res) {}
          });

          reject();
        } else if (res.statusCode == 503) {
          console.log(503);
          wx.showModal({
            title: '提示',
            content: '503错误，服务未启动',
            success: function success(res) {}
          });

          reject();
        } else {
          console.log(res);
          if (res.data.msg.indexOf("saveWashLogInside") > 0) {
            wx.showModal({
              title: '提示',
              content: res.data.msg.match(/[\u4e00-\u9fa5]+/g).join("，"),
              success: function success(res) {}
            });

          } else {
            wx.showModal({
              title: '提示',
              content: '错误：' + res.data.msg,
              success: function success(res) {}
            });
          }
          reject();
        }
      },
      fail(error) {
        console.log(error)
        // 忽略该错误 带有interrupted的 一般都是小程序切后台中断导致的 https://zhuanlan.zhihu.com/p/453875594
        if (error.errMsg) {
          if (error.errMsg.indexOf('network api interrupted in suspend state') == -1) {
            wx.showModal({
              title: '提示',
              content: '接口请求出错：' + error.errMsg,
              success(res) {}
            });
          }
        } else {
          wx.showModal({
            title: '提示',
            content: '接口请求出错：' + error,
            success(res) {}
          });
        }
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

module.exports = {
  request,
  loginWxMa: function loginWxMa(data) {
    //微信小程序登录接口
    data = util.dataAddSharerUserCode(data)
    return request('/mall/api/ma/wxuser/loginma', 'post', data, false);
  },
  loginByPhoneMa: function loginByPhoneMa(data) {
    //商城通过小程序授权手机号一键登录商城
    data = util.dataAddSharerUserCode(data)
    return request('/mall/api/ma/userinfo/ma/phone/login', 'post', data, true);
  },
  loginByPhone: function loginByPhone(data) {
    //商城手机验证码登录商城
    data = util.dataAddSharerUserCode(data)
    return request('/mall/api/ma/userinfo/phone/login', 'post', data, true);
  },
  login: function login(data) {
    //商城账号登录
    data = util.dataAddSharerUserCode(data)
    return request('/mall/api/ma/userinfo/login', 'post', data, true);
  },
  logout: function logout(data) {
    //商城退出登录
    return request('/mall/api/ma/userinfo/logout', 'post', data, true);
  },
  getPhoneCode: function getPhoneCode(data) {
    //获取手机验证码
    return request('/mall/api/ma/phone/code', 'get', data, true);
  },
  register: function register(data) {
    //账号注册
    util.dataAddSharerUserCode(data)
    return request('/mall/api/ma/userinfo/register', 'post', data, true);
  },
  updateUserPhone: function updateUserPhone(data) {
    //修改商城用户手机号
    return request('/mall/api/ma/userinfo/phone', 'post', data, true);
  },
  themeMobileGet: function themeMobileGet() {
    //获取商城主题装修配置
    return request('/mall/api/ma/thememobile', 'get', null, false);
  },
  wxUserGet: (data) => { //微信用户查询
    return request('/mall/api/ma/wxuser', 'get', null, false)
  },
  wxUserSave: (data) => { //微信用户新增
    return request('/mall/api/ma/wxuser', 'post', data, true)
  },
  goodsCategoryGet: (data) => { //商品分类查询
    return request('/mall/api/ma/goodscategory/tree', 'get', data, true)
  },
  goodsPage: (data) => { //商品列表
    return request('/mall/api/ma/goodsspu/page', 'get', data, false)
  },
  goodsGet: (id) => { //商品查询
    return request('/mall/api/ma/goodsspu/' + id, 'get', null, false)
  },
  goodsSpecGet: (data) => { //商品规格查询
    return request('/mall/api/ma/goodsspuspec/tree', 'get', data, true)
  },
  shoppingCartAdd: (data) => { //购物车新增
    return request('/mall/api/ma/shoppingcart', 'post', data, true)
  },
  shoppingCartEdit: (data) => { //购物车修改
    return request('/mall/api/ma/shoppingcart', 'put', data, true)
  },
  shoppingCartCount: (data) => { //购物车数量
    return request('/mall/api/ma/shoppingcart/count', 'get', data, false)
  },
  orderSub: (data) => { //订单提交
    return request('/mall/api/ma/orderinfo', 'post', data, true)
  },
  orderPage: (data) => { //订单列表
    return request('/mall/api/ma/orderinfo/page', 'get', data, false)
  },
  orderGet: (id) => { //订单详情查询
    return request('/mall/api/ma/orderinfo/' + id, 'get', null, false)
  },
  orderCancel: (id) => { //订单确认取消
    return request('/mall/api/ma/orderinfo/cancel/' + id, 'put', null, true)
  },
  orderReceive: (id) => { //订单确认收货
    return request('/mall/api/ma/orderinfo/receive/' + id, 'put', null, true)
  },
  orderDel: (id) => { //订单删除
    return request('/mall/api/ma/orderinfo/' + id, 'delete', null, false)
  },
  orderCountAll: (data) => { //订单计数
    return request('/mall/api/ma/orderinfo/countAll', 'get', data, false)
  },
  orderLogisticsGet: (logisticsId) => { //订单物流查询
    return request('/mall/api/ma/orderinfo/orderlogistics/' + logisticsId, 'get', null, false)
  },
  unifiedOrder: (data) => { //下单接口
    return request('/mall/api/ma/orderinfo/unifiedOrder', 'post', data, true)
  },
  userAddressPage: (data) => { //用户收货地址列表
    return request('/mall/api/ma/useraddress/page', 'get', data, false)
  },
  userCollectAdd: (data) => { //用户收藏新增
    return request('/mall/api/ma/usercollect', 'post', data, true)
  },
  userCollectDel: (id) => { //用户收藏删除
    return request('/mall/api/ma/usercollect/' + id, 'delete', null, false)
  },
  userCollectPage: (data) => { //用户收藏列表
    return request('/mall/api/ma/usercollect/page', 'get', data, false)
  },
  goodsAppraisesAdd: (data) => { //商品评价新增
    return request('/mall/api/ma/goodsappraises', 'post', data, true)
  },
  goodsAppraisesPage: (data) => { //商品评价列表
    return request('/mall/api/ma/goodsappraises/page', 'get', data, false)
  },
  qrCodeUnlimited: (data) => { //获取小程序二维码
    return request('/mall/api/ma/wxqrcode/unlimited', 'post', data, true)
  },
  noticeGet: (data) => { //查询商城通知
    return request('/mall/api/ma/notice', 'get', data, true)
  },
  orderItemGet: (id) => { //查询订单详情
    return request('/mall/api/ma/orderitem/' + id, 'get', null, false)
  },
  orderRefundsSave: (data) => { //发起退款
    return request('/mall/api/ma/orderrefunds', 'post', data, true)
  },
  userInfoGet: () => { //查询商城用户信息
    return request('/mall/api/ma/userinfo', 'get', null, false)
  },
  userInfoPut: (data) => { //修改商城用户
    return request('/mall/api/ma/userinfo', 'put', data, true)
  },
  pointsRecordPage: (data) => { //查询积分记录
    return request('/mall/api/ma/pointsrecord/page', 'get', data, false)
  },
  pointsConfigGet: () => { //查询积分配置
    return request('/mall/api/ma/pointsconfig', 'get', null, false)
  },
  couponUserSave: (data) => { //电子券用户领取
    return request('/mall/api/ma/couponuser', 'post', data, true)
  },
  couponUserPage: (data) => { //电子券用户列表
    return request('/mall/api/ma/couponuser/page', 'get', data, false)
  },
  couponInfoPage: (data) => { //电子券列表
    return request('/mall/api/ma/couponinfo/page', 'get', data, false)
  },
  listEnsureBySpuId: (data) => { //通过spuID，查询商品保障
    return request('/mall/api/ma/ensuregoods/listEnsureBySpuId', 'get', data, true)
  },
  wxTemplateMsgList: (data) => { //订阅消息列表
    return request('/mall/api/ma/wxtemplatemsg/list', 'post', data, false)
  },
  articlePage: (data) => {
    //文章列表
    return request('/mall/api/ma/articleinfo/page', 'get', data, false);
  },
  articleGet: (id) => {
    //文章详情
    return request('/mall/api/ma/articleinfo/' + id, 'get', null, false);
  },
  articleCategoryPage: (data) => {
    //文章分类列表
    return request('/mall/api/ma/articlecategory/page', 'get', data, false);
  },
  userBalanceLogPage: function userBalanceLogPage(data) {
    //余额 用户余额变更记录
    return request('/mall/api/ma/userbalancelog/page', 'get', data);
  },
  expressSiteList: function expressSiteList(data) {
    //查询站点列表
    return request('/mall/api/ma/expresssite/listAll', 'get', data);
  },
  providerApply: function providerApply(data) {
    //申请成为师傅
    return request('/mall/api/ma/provider/apply', 'post', data);
  },
  providerInfoGet: function providerInfoGet() {
    //查询当前师傅信息
    return request('/mall/api/ma/provider/getInfo', 'get', null);
  },
  updateProviderInfo: function updateProviderInfo(data) {
    //更新师傅信息
    return request('/mall/api/ma/provider', 'put', data);
  },
  providerOrderList: function providerOrderList(data) {
    //查询师傅可以接的订单列表
    return request('/mall/api/ma/provider/orderinfo/listByDistance', 'get', data);
  },
  providerOrderPage: (data) => { //师傅订单列表
    return request('/mall/api/ma/provider/orderinfo/page', 'get', data, false)
  },
  providerOrderCountAll: (data) => {
    //师傅订单计数
    return request('/mall/api/ma/provider/orderinfo/countAll', 'get', data, false)
  },
  providerOrderCountAllWithMonth: (data) => {
    //师傅月订单计数
    return request('/mall/api/ma/provider/orderinfo/countAllWithMonth', 'get', data, false)
  },
  providerAcceptOrder: function providerAcceptOrder(data) {
    //师傅接单
    return request('/mall/api/ma/provider/orderinfo/accept', 'post', data);
  },
  providerOrderGet: (id, data) => {
    //师傅订单详情查询
    return request('/mall/api/ma/provider/orderinfo/' + id, 'get', data, false)
  },
  providerOrderReceive: (data) => {
    //师傅订单核销
    return request('/mall/api/ma/provider/orderinfo/receive', 'put', data, false)
  },
  providerOrderCancel: (data) => {
    //师傅取消订单
    return request('/mall/api/ma/provider/orderinfo/cancel', 'put', data, false)
  },
  serviceCityList: function serviceCityList(data) {
    //查询服务区域列表
    return request('/mall/api/ma/servicecity/listAll', 'get', data);
  },
  providerWithdrawPage: (data) => {
    //师傅提现记录列表
    return request('/mall/api/ma/provider/providerwithdraw/page', 'get', data, false)
  },
  providerWithdrawApply: (data) => {
    //师傅提现申请
    return request('/mall/api/ma/provider/providerwithdraw/apply', 'post', data, true)
  },
  providerCountAppraises: (data) => {
    //师傅统计评价
    return request('/mall/api/ma/provider/countAppraises', 'get', data, false)
  },
  providerCountScore: () => {
    //师傅统计评分
    return request('/mall/api/ma/provider/orderinfo/countScore', 'get', null, false)
  },
  checkUser: function checkUser(data) {
    //判断当前用户是否登录
    return request('/mall/api/ma/userinfo/check', 'get', data);
  },
}